package com.heima.behavior.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一取出登录用户信息，存入ThreadLocal
 */
@Component
@Order(1) // 数字越大，优先级越小
@WebFilter(filterName = "AppTokenFilter",urlPatterns ="/*" )
public class AppTokenFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求和响应
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //从请求头取出userId
        String userId = request.getHeader("userId");

        //如果存在，则存入ThreadLocal
        if(StringUtils.isNotEmpty(userId) && !userId.equals("0") ){  //非游客身份
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            ThreadLocalUtils.set(apUser);
        }

        //必须放行
        filterChain.doFilter(request,response);
    }
}

